package com.weidong.mybbs.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public final class ImageCaptchaUtil {

    //获取验证码
    public static BufferedImage drawCaptcha(String code){
        char[] cstr = code.toCharArray();
        int codeLength = code.length();
        int imgWidth = 200;
        int imgHeight = 80;
        //创建画布
        BufferedImage image = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_BGR);
        //获得画笔
        Graphics g = image.getGraphics();
        //给笔设置颜色
        g.setColor(new Color(255,255,255));
        //设置画布的颜色
        g.fillRect(0, 0, imgWidth, imgHeight);
        int fontSize = Math.round(imgHeight * 0.8f);
        //设置字体
        g.setFont(new Font(null,Font.BOLD,fontSize));
        Random rd = new Random();
        //将文字绘制在图片上
        int ii = 0;
        for (char s:cstr) {
            ii ++ ;
            g.setColor(new Color(rd.nextInt(255),rd.nextInt(255),rd.nextInt(255)));
            int x;
            int xSymbol = rd.nextInt(1);
            int wJianJu = Math.round((imgWidth * 1.0f/codeLength)/1.5f);
            x = xSymbol == 1? wJianJu * ii + rd.nextInt(10):wJianJu * ii - rd.nextInt(10);
            int y = fontSize;
            int sym = rd.nextInt(1);
            y = sym==1?y+rd.nextInt(15):y-rd.nextInt(15);
            g.drawString(String.valueOf(s), x, y);
        }

        //干扰
        for(int i=0;i<16;i++){
            g.setColor(new Color(rd.nextInt(255),rd.nextInt(255),rd.nextInt(255)));
            g.drawLine(rd.nextInt(200),rd.nextInt(80), rd.nextInt(200),rd.nextInt(80));
        }
        return image;
    }
}
